import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type {
  InspectionPlanModel,
  MachineryModel,
} from '#/api/equipment/models';

import { isUndefined } from '@vben/utils';

import { getMachineryListApi } from '#/api/equipment/machinery';
import { useInspectTypeOptions } from '#/api/equipment/models';
import { getLineListApi } from '#/api/master/line';

/** 获取表格查询表单的字段配置。 */
export function useSearchSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        labelField: 'lineName',
        valueField: 'id',
        api: getLineListApi,
        immediate: false,
      },
      fieldName: 'lineId',
      label: '生产线',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'machineryName',
      label: '设备名称',
    },
  ];
}

/**
 * 获取编辑表单的字段配置。
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        afterFetch: (data: MachineryModel[]) => {
          // TODO: 采用树结构，参考 "点检标件-工位多选"
          return data.map((machinery) => ({
            value: machinery.id,
            label: `${machinery.machineryName} (${machinery.line.lineName} - ${machinery.workstation.wsCode})`,
          }));
        },
        api: getMachineryListApi,
      },
      dependencies: {
        if(values) {
          return isUndefined(values.id);
        },
        triggerFields: ['machineryId'],
      },
      fieldName: 'machineryId',
      label: '点检设备',
      rules: 'required',
      help: '设置后不能再修改',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      dependencies: {
        // 仅在编辑时显示，替代原有的字段（编辑 form 时不查询数据）
        if(values) {
          return !isUndefined(values.id);
        },
        disabled: true,
        triggerFields: ['machineryId'],
      },
      fieldName: 'machinery.machineryName',
      label: '点检设备',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      fieldName: 'planName',
      label: '计划名称',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: useInspectTypeOptions(),
      },
      dependencies: {
        disabled(values) {
          return !isUndefined(values.id);
        },
        triggerFields: ['machineryId'],
      },
      fieldName: 'inspectType',
      label: '点检类型',
      defaultValue: 'Manual',
      rules: 'required',
      help: '设置后不能再修改',
    },
    {
      component: 'Input',
      fieldName: 'schedule',
      label: '执行计划',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '提醒', value: 1 },
          { label: '警告', value: 2 },
        ],
      },
      fieldName: 'remind',
      label: '提醒方式',
      defaultValue: 1,
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '是', value: true },
          { label: '否', value: false },
        ],
      },
      dependencies: {
        trigger(values) {
          // 非编辑情况下，手动点检项默认选择校验结果
          if (isUndefined(values.id)) {
            values.isCheckFinalResult = values.inspectType === 'Manual';
          }
        },
        triggerFields: ['inspectType'],
      },
      fieldName: 'isCheckFinalResult',
      label: '校验结果',
      defaultValue: true,
      rules: 'required',
      help: '根据每个点检项的结果来判定最终结果，手动点检优先选择，自动点检根据需要选择',
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
    },
    {
      component: 'Textarea',
      componentProps: {
        showCount: true,
        maxlength: 128,
      },
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2 items-baseline',
    },
  ];
}

/**
 * 获取表格列配置。
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<InspectionPlanModel>,
): VxeTableGridOptions<InspectionPlanModel>['columns'] {
  return [
    { type: 'seq', width: 60 },
    { field: 'planName', title: '点检计划', width: 160 },
    { field: 'machinery.machineryName', title: '点检设备', width: 160 },
    { field: 'machinery.line.lineName', title: '点检产线', width: 140 },
    { field: 'machinery.workstation.wsCode', title: '点检工位', width: 100 },
    {
      field: 'inspectType',
      title: '点检类型',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: useInspectTypeOptions(),
      },
    },
    { field: 'schedule', title: '执行计划', width: 120 },
    {
      field: 'isCheckFinalResult',
      title: '校验结果',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          { color: 'cyan', label: '是', value: true },
          { color: 'orange', label: '否', value: false },
        ],
      },
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      cellRender: { name: 'CellTag', attrs: { useStatus: true } },
    },
    { field: 'remark', title: '备注', minWidth: 100 },
    { field: 'createdTime', title: '创建时间', width: 150 },
    {
      cellRender: {
        attrs: {
          nameField: 'planName',
          nameTitle: '点检计划',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'open',
            text: '点检项',
          }, // 显示点检项
          'edit', // 默认的编辑按钮
          'delete', // 默认的删除按钮
        ],
      },
      field: 'operation',
      fixed: 'right',
      title: '操作',
      width: 160,
    },
  ];
}
